package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Log;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;

//移除购物车中的选中项
public class RemoveItemFromCartServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";

    private String workingItemId;
    private Cart cart;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //要移除的项
        workingItemId = request.getParameter("workingItemId");
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        cart = (Cart) session.getAttribute("cart");
        CatalogService catalogService = new CatalogService();
        //移除购物车中的某一项
        Item item = cart.removeItemById(workingItemId);
        if (item == null){
            request.getRequestDispatcher(ERROR).forward(request,response);
        }else{
            catalogService.removeCartItem(account.getUsername(),workingItemId);

            //时间
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetime = tempDate.format(new java.util.Date());
            //信息
            String info = "将"+workingItemId+"移出购物车";
            Log log = new Log(account.getUsername(),datetime,info);
            //添加log
            new AccountService().addLog(log);

            request.getRequestDispatcher(VIEW_CART).forward(request,response);

    }

}
}